package com.gxhmplan.web;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.gxhmplan.user.service.UserService;

public class AccessFilter implements Filter {
	// 声明Spring容器引用
	private WebApplicationContext ctx;
	// 利用初始化方法初始化Spring容器
	public void init(FilterConfig cfg) throws ServletException {
		// 方法必须
		// 与 ContextLoaderListener配合才能
		// 正常获取 Spring容器 对象 ctx !!!
		// 获取当前Web应用中的Spring容器
		ctx = WebApplicationContextUtils.getWebApplicationContext(cfg.getServletContext());
	}

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		// getCookies 方法可以获取客户端传送的所有
		// Cookie对象.
		Cookie[] cookies = request.getCookies();
		// 从Cookie中获取token和UserId
		String token = null;
		String userId = null;
		if (cookies != null) {
			for (Cookie c : cookies) {
				//System.out.println(c.getName() + ":" + c.getValue());
				if ("token".equals(c.getName())) {
					token = c.getValue();
				}
				if ("id".equals(c.getName())) {
					userId = c.getValue();
				}
			}
		}
		if (token == null) {
			// 重定向到登陆页面
			response.sendRedirect("/signin.htm");
			return;
		}
		// 从Spring容器中获取业务层对象 userService
		UserService svc = ctx.getBean("userService", UserService.class);
		// 如Cookie中的Token与数据库的Token
		// 不一致 则重定向到登陆页面
		if (svc.checkToken(userId, token)) {
			// 执行后续的请求, 也就是执行 edit.htm
			chain.doFilter(req, res);
		} else {
			response.sendRedirect("/signin.htm");
		}
	}

	public void destroy() {
	}
}
